package com.duy.chat;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Button;
import android.widget.EditText;

import java.net.*;
import java.io.*;

public class MainActivity extends Activity {
	
	protected Socket socket = null;
	protected PrintWriter out = null;
	protected BufferedReader in = null;
	
	protected TextView cWin = null;
	protected Button send = null;
	protected EditText input = null;
	
	private Handler handler = new Handler();
	
	cThread c = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send = (Button) findViewById(R.id.send);
		input = (EditText) findViewById(R.id.input);
		cWin = (TextView) findViewById(R.id.chat);
        
		//c = new cThread( this.getApplicationContext() );
		
		send.setOnClickListener(sendListener);
		send.setEnabled(true);
    }
    
    private OnClickListener sendListener = new OnClickListener() {
		@Override
        public void onClick(View v) {
            String oPut = input.getText().toString() + System.getProperty("line.separator");
            new cThread().execute(oPut);
        }
    };
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    private class cThread extends AsyncTask<String, Void, Socket>{
    	private Socket s;
    	private String reply;
    	private Context context;
    	private BufferedWriter out;
    	private BufferedReader in;
    	
    	public cThread()
    	{
    		//this.context = con;
    		socket = null;
    		out = null;
    		in = null;
    	}
    	
		@Override
		protected Socket doInBackground(String... arg0) {
			try{
				if (s == null){ // Socket isn't setup? do it
					s = new Socket("10.0.2.2", 8080);
					out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
					in = new BufferedReader(new InputStreamReader(s.getInputStream()));
					//out.write("Hello Server, This is client");
				}
				
				out.write(arg0[0]); // Write input param to the socket
				out.flush();		// get rid of the new line char
				
				// read reply from server
				reply = in.readLine();
				handler.post(new Runnable(){
					public void run(){
						// Set Text for now, need to come up with better way later
						cWin.setText(cWin.getText() + "\nS: " +  reply );
					}
				});
				return s;
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			return s;
		}
    };// end of cThread
}